//
//  UIView+Gesture.m
//  Objective-C
//
//  Created by 陆承东 on 2018/6/9.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "UIView+SLGesture.h"

#import <objc/runtime.h>

NSString const *kViewTapGestureKey = @"kViewTapGestureKey";
NSString const *kViewTapGestureActionKey = @"kViewTapGestureActionKey";

@implementation UIView (SLGesture)

- (ViewTapBlock)tapBlock {
    return objc_getAssociatedObject(self, &kViewTapGestureActionKey);
}


- (void)setTapBlock:(ViewTapBlock)tapBlock {
    UITapGestureRecognizer *tap = objc_getAssociatedObject(self, &kViewTapGestureKey);
    if (!tap) {
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTaped:)];
        [self addGestureRecognizer:tap];
        objc_setAssociatedObject(self, &kViewTapGestureKey, tap, OBJC_ASSOCIATION_RETAIN);
    }
    
    objc_setAssociatedObject(self, &kViewTapGestureActionKey, tapBlock, OBJC_ASSOCIATION_COPY);
}

- (void)viewTaped:(UIGestureRecognizer *)ges {
    if (ges.state == UIGestureRecognizerStateRecognized) {
        ViewTapBlock tapBlock = objc_getAssociatedObject(self, &kViewTapGestureActionKey);
        if (tapBlock) {
            tapBlock();
        }
    }
}

@end
